<?php

namespace app\admin\controller;
use think\exception\ValidateException;
use think\facade\Db;
use app\admin\model\UserToken as AdminTokenModel;
use app\admin\model\User as UserModel;
use app\admin\model\RbacMenu as RbacMenuModel;
use sms\Sms;
use think\facade\Env;
use think\facade\Cache;

class Login extends Admin
{
	//用户登录
    public function index() {
		$postField = 'mobile,sms_code,password,verify,key,type';
		$data = $this->request->only(explode(',',$postField),'post',null);
		
		if(empty($data['mobile'])){
			throw new ValidateException('请输入验证码');
		}
		
		if(empty($data['password']) && empty($data['sms_code'])){
			throw new ValidateException('请输入密码或短信验证码');
		}
        if(empty($data['type'])){
            throw new ValidateException('请选择登录类型');
        }

        if(!in_array($data['type'], [1,2])){
            throw new ValidateException('登录类型错误');
        }

        $verify_status = !is_null(config('my.verify_status')) ? config('my.verify_status') : true;
		
		if ($verify_status) {
			if(empty($data['verify'])) {
				throw new ValidateException('请输入验证码');
			}
			if(!captcha_check($data['key'],$data['verify'])){
				throw new ValidateException('验证码错误');
			}
		}
		$res = $this->checkLogin($data);
		if($res){
			return json([
                'code'=>200,
                'token'=>$this->setToken($res),
                'avatar'=>'',
                'nickname'=>$res['nickname']
            ]);
		}
    }

    //验证登录
    private function checkLogin($data){
        Db::startTrans();
        switch ($data['type']) {
            case 1: //短信验证
                $where['a.mobile'] = $data['mobile'];
                $info = Db::name('user')
                    ->alias('a')
                    ->field('a.*')
                    ->where($where)
                    ->find();
                if (!$info) { //不存在，就注册
                    $insert = [
                        'nickname' => '用户'.$data['mobile'],
                        'mobile' => $data['mobile'],
                        'salt' => random(12,'salt'),
                        'create_time' => time()
                    ];
                    try{
                        $res = UserModel::create($insert);
                        UserModel::where('id',  $res->id)->save(['main_user_id'=>$res->id]);
                    }catch(\Exception $e){
                        throw new ValidateException($e->getMessage());
                    }
                    $info = $res;
                }
                //验证短信验证码
                $loginSmsCode = Cache::get('login_sms_code');
                if (!$loginSmsCode) {
                    throw new ValidateException("短信验证码已失效");
                }
                if ($loginSmsCode != md5($data['sms_code'])) {
                    throw new ValidateException("验证码错误");
                }
                Cache::delete('login_sms_code');
                break;
            case 2: //密码验证
                $where['a.mobile'] = $data['mobile'];
                $info = Db::name('user')
                    ->alias('a')
                    ->field('a.*')
                    ->where($where)
                    ->find();
                if (!$info) {
                    throw new ValidateException("请检查用户名");
                }
                $password  = md5($data['password'].$info['salt'].config('my.password_secrect'));
                if ($password != $info['password']) {
                    throw new ValidateException("请检查用户名或者密码");
                }
                if (!($info['status'])) {
                    throw new ValidateException("该账户被禁用");
                }
                break;
        }

        event('LoginLog', $data['mobile']);	//写入登录日志
        Db::commit();
        return $info;
    }


    //获取用户信息 菜单信息 以及菜单对应的组件
	public function getUserInfo() {
		if(!$this->userInfo['id']){
			throw new ValidateException('用户Id不存在');
		}
        $validate = validate([
            'device' => 'require',
        ], [
            'device.require'=>'device不存在',
        ], false, false);
        $post = $this->request->param();
        $result = $validate->check($post);
        if (!$result) {
            $error = $validate->getError();
            return msg(0, $error);
        }
		
		$userInfo = db('user')->field('id,nickname,mobile')->where('id',$this->userInfo['id'])->find();
		if(!$userInfo){
			throw new ValidateException('用户信息不存在');
		}
        $menu = RbacMenuModel::where('home_show',1)
            ->where('device', $post['device'])
            ->field('id,title,pid,path,icon')
            ->order('sort', 'asc')
            ->select()->toArray();
        $menuTree = genTree($menu, 0, 'id', 'pid');


		$components = $this->getComponents($menu);
		
		//如果是超级管理员则把下面两个组件挂载上
		/*if($userInfo['role_id'] == 1){
			$fieldComponents = [
				'name'=>'Field',
				'path'=> (string)url('admin/Field/index'),
				'meta'=>['title'=>'字段管理'],
				'component_path'=>'admin/sys/field/Index.vue'
			];
			$actionComponents = [
				'name'=>'Action',
				'path'=> (string)url('admin/Action/index'),
				'meta'=>['title'=>'方法管理'],
				'component_path'=>'admin/sys/action/Index.vue'
			];
			array_push($components,$fieldComponents,$actionComponents);
		}*/
		//$components = array_merge($components,$this->getHiddenComponents($roleInfo)); 	//挂载菜单隐藏 但是定义了的组件
		
		$userInfo['site_title']  = config('base_config.site_title');
		$userInfo['avatar'] = config('base_config.logo');
        $userInfo['name'] = '易巴士';
		$userInfo['show_notice'] = !is_null(config('my.show_notice')) ? config('my.show_notice') : true;	//是否显示消息提示按钮
		$data['code'] = 200;
		$data['menu'] = $menuTree;
		$data['components'] = $components;
		$data['data'] = $userInfo;
		return json($data);
	}

	
	//获取当前角色的菜单
	private function getMyMenus($roleInfo,$totalMenus){
		if($roleInfo['role_id'] == 1){
			return $totalMenus;
		}
		foreach($totalMenus as $key=>$val){
			if(in_array($val['name'],explode(',',$roleInfo['access']))){
				$tree[] = array_merge($val,['children'=>$this->getMyMenus($roleInfo,$val['children'])]);
			}
		}
		return array_values($tree);
		
	}

    public function sendSms()
    {
        $validate = validate([
            'mobile' => 'require',
        ], [
            'mobile.require'=>'mobile不存在',
        ], false, false);
        $post = $this->request->param();
        $result = $validate->check($post);
        if (!$result) {
            $error = $validate->getError();
            return msg(0, $error);
        }
        $ali_sms = [
            'accessKeyId' => config('my')['ali_sms_accessKeyId'],
            'accessKeySecret' => config('my')['ali_sms_accessKeySecret'],
            'signName' => config('my')['ali_sms_signname'],
            'templateCode' => config('my')['ali_sms_tempCode'],
        ];
        $sms = new Sms($ali_sms);
        if (Env::get('APP_DEBUG', 'false')) {
            $randStr = '888888';
        } else {
            $randStr = random(6,'number');
            $res = $sms->send_verify($post['mobile'], $randStr);
            if (!$res) {
                $data =  [
                    'msg' => '发送失败',
                    'data' => $res,
                    'code' => 0
                ];
                return json($data);
            } else {
                if (!empty($res['Message']) && $res['Message'] != 'OK') {
                    $data =  [
                        'msg' => '发送失败',
                        'data' => $res,
                        'code' => 0
                    ];
                    return json($data);
                }
            }
        }
        Cache::set('login_sms_code', md5($randStr), 5 * 60);
        $data =  [
            'msg' => '发送成功',
            'data' => $res,
            'code' => 200
        ];
        return json($data);
    }


    //验证码
	public function verify(){
		$data['rememberMe'] = true;
		$data['data'] = captcha();
		$data['site_title'] = config('base_config.site_title');
		$data['success_url'] = (string)url('admin/Home/index');		//登录成功后的跳转地址
		$data['verify_status'] = !is_null(config('my.verify_status')) ? config('my.verify_status') : true;	//验证码开关
		$data['code'] = 200;
	    return json($data);
	}

	//退出
    public function logout(){
		$token = $this->request->header('Authorization');
		AdminTokenModel::where('token',$token)->delete();
        return json(['code'=>200]);
    }
	

}
